//
//  UserAccount.m
//  OC-LBWeibo
//
//  Created by 李博 on 15/7/9.
//  Copyright © 2015年 libo. All rights reserved.
//

#import "UserAccount.h"
#import "NetworkTools.h"



@interface UserAccount()

@property(nonatomic,strong)NSString *accountPath;

@end

@implementation UserAccount


+ (UserAccount *)sharedUserAccount
{
    static UserAccount *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[[self alloc]init] loadAccount];
    });
    return instance;
}


- (NSString *)accountPath
{
    if (_accountPath == nil) {
        _accountPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"account.plist"];
    }
    return _accountPath;
}

- (NSDate *)expiresDate
{
    if (_expiresDate == nil) {
        //计算过期时间
        _expiresDate = [[NSDate alloc]initWithTimeIntervalSinceNow:self.expires_in];
    }
    return _expiresDate;
}

-(instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        //[self setValuesForKeysWithDictionary:dict];
        [self setValue:dict[@"access_token"] forKey:@"access_token"];
        [self setValue:dict[@"expires_in"] forKey:@"expires_in"];
        [self setValue:dict[@"uid"] forKey:@"uid"];
    }
    return self;
}

+(instancetype)userWithDict:(NSDictionary *)dict
{
    return [[self alloc]initWithDict:dict];
}


//加载用户信息
- (void)loadUserInfo:(void (^)(UserAccount *, NSError *))finished
{
    NSDictionary *params = @{@"access_token":self.access_token,@"uid":self.uid};
    
    [[NetworkTools sharedNetworkTools] GET:@"2/users/show.json" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *result = responseObject;
        self.name = result[@"name"];
        self.avatar_large = result[@"avatar_large"];
        //保存用户信息到沙盒
        [self saveAccount];
        
        //通知调用方，处理完成
        finished(self,nil);
        
    } failure:^(NSURLSessionDataTask *account, NSError *error) {
        NSLog(@"%@",error);
        finished(nil,error);
    }];
}


//保存用户信息到沙盒
- (void)saveAccount {
    
    [NSKeyedArchiver archiveRootObject:self toFile:self.accountPath];
}
//从沙盒读取
- (UserAccount *)loadAccount
{
    NSLog(@"从沙盒加载账户信息。。");
    //判断token是否过期
    UserAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:self.accountPath];
    
    if (account != nil) {
        if ([account.expiresDate compare:[NSDate date]] == NSOrderedDescending) {
            return account;
        }
    }
    
    return nil;
}


///打印用户信息
- (NSString *)description
{
    NSDictionary *dict = [self dictionaryWithValuesForKeys:@[@"access_token",@"expires_in",@"expiresDate",@"uid", @"avatar_large", @"name"]];
    
    return [NSString stringWithFormat:@"%@", dict];
}


// MARK: - NSCoding 归档解档
//解挡
- (instancetype)initWithCoder:(NSCoder *)coder
{

    if (self = [super init]) {
        self.access_token = [coder decodeObjectForKey:@"access_token"];
        self.expires_in = [coder decodeDoubleForKey:@"expires_in"];
        self.expiresDate = [coder decodeObjectForKey:@"expiresDate"];
        self.uid = [coder decodeObjectForKey:@"uid"];
        self.name = [coder decodeObjectForKey:@"name"];
        self.avatar_large = [coder decodeObjectForKey:@"avatar_large"];
    }
    return self;
}
//归档
- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:self.access_token forKey:@"access_token"];
    [coder encodeDouble:self.expires_in forKey:@"expires_in"];
    [coder encodeObject:self.expiresDate forKey:@"expiresDate"];
    [coder encodeObject:self.uid forKey:@"uid"];
    [coder encodeObject:self.name forKey:@"name"];
    [coder encodeObject:self.avatar_large forKey:@"avatar_large"];
}





@end
